<template>
  <div class="departments">
    <!-- 卡片 -->
    <el-card>
      <!-- tabs -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="组织架构" name="first">
          <!-- layout 栅格(shan ge)布局 -->
          <el-row type="flex" justify="space-between">
            <el-col :span="6">
              <h4><i class="el-icon-office-building" />    江苏传智播客教育科技股份有限公司</h4>
            </el-col>
            <el-col class="right-col" :span="6">
              <span class="leader">负责人</span>
              <!-- 下拉菜单 -->
              <el-dropdown>
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button type="text" @click="dialogFormVisible = true">添加子部门</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
          <!-- 和底部的内容分割开来 -->
          <el-divider />
          <!-- tree -->
          <el-tree
            :data="departs"
            :props="defaultProps"
            @node-click="handleNodeClick"
          >
            <!-- 通过插槽传递自定义的结构 -->
            <template #default="{ data }">
              <el-row class="tree-row" type="flex" justify="space-between">
                <el-col :span="6"> <i class="el-icon-user" />  <noscript />{{ data.name }}</el-col>
                <el-col class="right-col" :span="6">
                  <span class="leader">{{ data.manager }} </span>
                  <!-- 下拉菜单 -->
                  <el-dropdown>
                    <span class="el-dropdown-link">
                      操作<i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item>
                        <el-button type="text" @click="addChildren(data)">添加子部门</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button type="text" @click="onEdit(data)">查看部门</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button type="text" @click="delChildren(data)">删除部门</el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-col>
              </el-row>
            </template>
          </el-tree>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 弹框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @closed="onCancel()">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="部门名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门编码"
          :label-width="formLabelWidth"
          prop="code"
        >
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门负责人"
          :label-width="formLabelWidth"
          prop="manager"
        >
          <el-select
            v-model="form.manager"
            placeholder="请选择活动区域"
            @focus="onFocus"
          >
            <!-- 新增部门,manager用的是名字,不是id 这个label和value都渲染相同的数据 -->
            <el-option
              v-for="item in managers"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="部门介绍"
          :label-width="formLabelWidth"
          prop="introduce"
        >
          <el-input v-model="form.introduce" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartment, addDepartments, getDepartmentByID, editDepartments, delDepartment } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees.js'
function formatData(list, pid) {
  return list.filter((v) => {
    if (v.pid === pid) {
      v.children = formatData(list, v.id)
      return true
    } else {
      return false
    }
  })
}
export default {
  name: 'Departments',
  data() {
    return {
      // 部门负责人数组
      managers: [],
      // 是否显示弹框
      dialogFormVisible: false,
      // 表单的数据
      form: {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        manager: '', // 部门负责人
        name: '', // 部门名称
        pid: '' // 父级部门id
      },
      formLabelWidth: '120px',
      activeName: 'first',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      departs: [

      ],
      // 表单校验规则
      rules: {
        code: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '请填写1-50个字符', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '请填写1-50个字符', trigger: 'change' }
        ],
        manager: [{ required: true, message: '不能为空', trigger: 'blur' }],
        name: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '请填写1-50个字符', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async delChildren(data) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delDepartment(data.id)
        this.getData()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {

      })
    },
    onCancel() {
      this.form = {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        manager: '', // 部门负责人
        name: '', // 部门名称
        pid: '' // 父级部门id
      }
      this.dialogFormVisible = false
    },

    addChildren(data) {
      this.form.pid = data.id
      this.dialogFormVisible = true
    },
    async onEdit(data) {
      const res = await getDepartmentByID(data.id)
      this.form = { ...res }
      this.dialogFormVisible = true
    },
    // 获取tree数据的方法
    async getData() {
      const res = await getDepartment()
      // console.log('res:', res.depts)
      this.departs = formatData(res.depts, '')
      // // 排除掉pid为-1
      // const res1 = res.depts.filter((v) => v.pid !== '-1')
      // // 找顶级节点 filter 大数组中筛选出若干个你要的值
      // const root = res1.filter((v) => v.pid === '')
      // // console.log('root:', root)
      // // 找后代
      // root.forEach((v) => {
      //   // 获取 子节点
      //   // pid和当前节点的id相同
      //   v.children = res1.filter((vc) => vc.pid === v.id)
      // })
      // 把处理完毕的数据 设置上去

      // 直接去vue的插件看,不会有`...`
      // console.log('root:', root)
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          if (this.form.id) {
            await editDepartments(this.form)
            // console.log(res)
          } else {
            await addDepartments(this.form)
            // console.log('res:', res)
            this.$message.success('新增成功')
            // this.onCancel()
          }
          // console.log('成功')
          // 调用接口

          this.dialogFormVisible = false
          this.getData()
        } else {
          this.$message.error('数据格式有误,请检查哦!')
          return false
        }
      })
    },
    async onFocus() {
      // console.log('123')
      // 调用接口
      const res = await getEmployeeSimple()
      // console.log('res:', res)
      this.managers = res
    },
    handleNodeClick(data) {
      // console.log(data)
    }
  }
}
</script>

<style lang="scss">
.departments {
  .el-tabs__content {
    padding: 20px 40px 40px;
    h4 {
      margin: 0;
    }
    .right-col {
      text-align: right;
    }
    .leader {
      font-size: 14px;
      margin-right: 10px;
    }
    .el-tree-node__content {
      // width: 100%;
      // display: block;
      .tree-row {
        flex: 1;
      }
    }
  }
 .el-dialog__header{
   background-color: rgb(25, 123, 214);
   .el-dialog__title{
     color: #fff;
   }
 }
}
</style>
